package com.gowants.pems.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gowants.pems.aspect.Importance;
import com.gowants.pems.aspect.OperType;
import com.gowants.pems.aspect.ScmsAopLog;
import com.gowants.pems.config.AccessLimit;
import com.gowants.pems.mapper.SwitchCabinetMapper;
import com.gowants.pems.model.SwitchCabinet;
import com.gowants.pems.util.DateUtil;
import com.gowants.pems.util.JSONList;
import com.gowants.pems.util.JSONMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/switchCabinet/")
public class SwitchCabinetController  extends BaseController{

    @Autowired
    private SwitchCabinetMapper mapper;
    
    /**
     * 获取开关柜列表
     * @param page
     * @param limit
     * @param reqData
     * @param req
     * @return
     */
    @RequestMapping(value = "/getList", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "开关柜列表查看", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap getList(@RequestParam(defaultValue = "1", required = false, value = "page") int page,
                           @RequestParam(defaultValue = "10", required = false, value = "limit") int limit,
                           @RequestParam(defaultValue = "", required = false, value = "reqData") String reqData,
                           HttpServletRequest req)
    {
        if (!isPower("/switchCabinet/getList.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        JSONMap resultMap = new JSONMap();
        SwitchCabinet record = new SwitchCabinet();
        if (!"".equals(reqData))
        {
            JSONList jsonCondition = getCondition(reqData);

            for (Object cond : jsonCondition) {
                this.buildCondition(cond, record);
            }
        }
        if(StringUtils.isNotBlank(getUser().getOwnerId())) {
            record.setOwner(getUser().getOwnerId());
        }
        // 设置分页查询信息
        PageHelper.startPage(page, limit);
        List<SwitchCabinet> list = mapper.select(record);
        PageInfo<SwitchCabinet> pageInfo = new PageInfo<SwitchCabinet>(list);
        // 赋值方法
        pageSetData(req, resultMap, page,  limit, pageInfo.getPages(),"", list, pageInfo.getTotal());

        return doResponse(req, "", resultMap);
    }



    @RequestMapping(value = "/getOneSwitchCabinet", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "开关柜一条记录检索", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap getOneSwitchCabinet(String request, HttpServletRequest req){
        SwitchCabinet switchCabinet=new SwitchCabinet();
        String code ="";
        if (!isPower("/switchCabinet/getOneSwitchCabinet.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        try
        {
            JSONMap requestBody = getRequestBody(request);
            String id = requestBody.getString("id");
            switchCabinet = mapper.selectById(id);
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }

        return doResponse(req, code, switchCabinet);
    }



    @RequestMapping(value = "/saveSwitchCabinet", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "开关柜保存", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap saveSwitchCabinet(String request, HttpServletRequest req){
        if (!isPower("/switchCabinet/saveSwitchCabinet.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        String code = "TSMS_0000036";
        try
        {
            SwitchCabinet record = getRequestBody(request, SwitchCabinet.class);
            record.setId(UUID.randomUUID().toString());
            record.setCreateUid(getUserId());
            record.setCreateTime(DateUtil.getDate());

            int count = mapper.checkCode(record.getCabinetNumber());
            if(count > 0)
            {
                return doResponse(req, "TSMS_0000493", null);
            }
            int count1 = mapper.checkName(record.getName());
            if(count1 > 0)
            {
                return doResponse(req, "TSMS_0000492", null);
            }
            int exeNum = mapper.insert(record);
            if(exeNum > 0)
            {
                code = "TSMS_0000001";
            }
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }

        return doResponse(req, code, null);
    }

    @RequestMapping(value = "/editSwitchCabinet", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "开关柜修改", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap editSwitchCabinet(String request, HttpServletRequest req){
        if (!isPower("/switchCabinet/editSwitchCabinet.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        String code = "TSMS_0000053";
        try
        {
            SwitchCabinet record = getRequestBody(request, SwitchCabinet.class);
            //校验 groupId+dictId是否重复
            int count = mapper.checkCodeForUpdate(record.getCabinetNumber(),record.getId());
            if(count > 0)
            {
                return doResponse(req, "TSMS_0000493", null);
            }
            int count1 = mapper.checkNameForUpdate(record.getName(),record.getId());
            if(count1 > 0)
            {
                return doResponse(req, "TSMS_0000492", null);
            }
            int exeNum = mapper.update(record);
            if(exeNum > 0)
            {
                code = "TSMS_0000001";
            }
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }

        return doResponse(req, code, null);
    }


    /**
     * <删除>
     * @param request
     * @param req
     * @return
     * @remake
     */
    @RequestMapping(value = "/deleteSwitchCabinet", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "开关柜删除", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap deleteSwitchCabinet(String request, HttpServletRequest req)
    {
        if (!isPower("/switchCabinet/deleteSwitchCabinet.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        String code = "TSMS_0000048";
        try
        {
            JSONMap requestBody = getRequestBody(request);
            String id = requestBody.getString("id");
            int exeNum = mapper.delete(id);
            if(exeNum > 0)
            {
                code = "TSMS_0000050";
            }
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }
        return doResponse(req, code, null);
    }

    private void buildCondition(Object cond, SwitchCabinet record)
    {
        JSONMap condition = JSONMap.parseJSONMap(cond.toString());

        String field = condition.getString("field");
        String keyword = condition.getString("keyword");

        if (StringUtils.isNotEmpty(field) && StringUtils.isNotEmpty(keyword))
        {
            switch (field)
            {
                case "id":
                    record.setId(keyword);
                    break;
                case "cabinetNumber":
                    record.setCabinetNumber(Integer.parseInt(keyword));
                    break;
                case "name":
                    record.setName(keyword);
                    break;
                case "station":
                    record.setStation(keyword);
                    break;
                case "stationId":
                    record.setStationId(keyword);
                    break;
            }
        }
    }
}
